package com.caihedi.www.caihedi;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private ImageView img;
    private Button but;
    private TextView text;
    private final int PLAYER = 1;
    private boolean start_stop = false;
    int i=0;
    int picture[] = {R.drawable.zheermao,R.drawable.bosimao,R.drawable.buoumao,R.drawable.duanmaomao,R.drawable.lanmao};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img = findViewById(R.id.img);
        img.setImageResource(R.drawable.zheermao);
        but = findViewById(R.id.but);
        text = findViewById(R.id.text1);

        but.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                    start_stop=!start_stop;
                    if (start_stop)
                        but.setText("暂停");
                    else
                        but.setText("播放");
            }
        });
        final Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what==PLAYER){
                    i = (i+1)%picture.length;
                    img.setImageResource(picture[i]);

                }
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (start_stop){
                        Message message = Message.obtain();
                        message.what = PLAYER;
                        handler.sendMessage(message);
                    }
                }
            }
        }).start();
    }
}
